<template>
  <div class="box">
    <div class="button_group">
      <el-button v-if="!record.length"
                 plain
                 class="mr20"
                 @click="download(templateUrl)">
        下载模板
      </el-button>
      <UploadExcel v-if="!record.length"
                   :order-import="true"
                   :api="api"
                   @messageStatus="messageStatus" />
      <el-button v-if="record.length > 0"
                 plain
                 class="mr20"
                 @click="handleCancel">
        取消导入
      </el-button>
      <el-button v-if="record.length > 0"
                 class="mr20"
                 type="primary"
                 :loading="loading"
                 @click="submit">
        提交导入
      </el-button>
    </div>
    <div class="content_sty">
      <div v-if="!record.length"
           class="box-wrap text-center">
        <img class="empty_img"
             :src="emptyImg"
             alt="" />
        <div class="tips">暂无数据，快去导入吧~</div>
      </div>
      <div v-if="status === 2"
           class="mt130">
        <el-progress type="circle"
                     :percentage="25"
                     :stroke-width="18"
                     :width="300" />
        <div class="tips">正在解析订单中···</div>
      </div>
    </div>
    <!-- <span v-if="record.length > 0">载入结果：共xxx个订单，用时xxs，异常订单xx个，正常订单xx个。</span> -->
    <span v-if="record.length > 0"
          class="import-results">载入结果：共{{record.length}}个订单。</span>
    <el-table v-if="record.length > 0"
              :data="pageList"
              :height="'720px'"
              style="width: 100%"
              border
              :tree-props="{ children: 'errors' }">
      <el-table-column type="index"
                       width="50" />
      <template v-for="(item, i) in tableHeaderData">
        <el-table-column v-if="item.type === 'fromInfo'"
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :width="'200px'"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <ShippingInfo class="tooltipSty"
                          :name="'orderImport'"
                          :row="scope.row" />
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'toInfo'"
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :width="'200px'"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <ConsigneeInfo class="tooltipSty"
                           :name="'orderImport'"
                           :row="scope.row" />
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'orderInfo'"
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :width="'200px'"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <OrderInfo class="tooltipSty"
                       :name="'orderImport'"
                       :row="scope.row" />
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'success'"
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :width="'80px'"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag :type="scope.row.success ? 'success' : 'danger'">
              {{scope.row.success ? '正常' : '异常'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'errors'"
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <Errors :row="scope.row" />
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'warnings'"
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <Warnings :row="scope.row" />
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'operation'"
                         :key="i"
                         :prop="item.type"
                         :width="'80px'"
                         :label="item.label">
          <template slot-scope="scope">
            <el-button type="text"
                       @click="edit(scope.$index)">修改</el-button>
          </template>
        </el-table-column>
        <el-table-column v-else
                         :key="i"
                         :prop="item.type"
                         :label="item.label"
                         :width="'150px'"
                         :show-overflow-tooltip="true">
        </el-table-column>
      </template>
    </el-table>
    <el-pagination v-show="record.length > 0"
                   class="order-import-pag"
                   background
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total"
                   :page-sizes="pageSizeOptions"
                   :page-size.sync="pageSize"
                   :current-page.sync="pageNo"
                   @size-change="handleSizeChange"
                   @current-change="handleSizeChange">
    </el-pagination>
    <!-- 展示进度 -->
    <ImportProgress v-model="visible"
                    :data="subTaskObject"
                    @refresh="handleRefresh" />
  </div>
</template>
<script>
import ConsigneeInfo from "@components/table/column/ConsigneeInfo.vue";
import ShippingInfo from "@components/table/column/ShippingInfo.vue";
import OrderInfo from "@components/table/column/OrderInfo.vue";
import UploadExcel from "./components/UploadExcel.vue";
import Errors from "./editOrder/Errors.vue";
import Warnings from "./editOrder/Warnings.vue";
import ImportProgress from "./components/ImportProgress.vue"
import { order, admin } from "@/api/index.js";
// import { dialogFulfill } from '@tablra/fulfill/executors/RequestExecutor'
import { mapState, mapGetters, mapActions } from "vuex";
export default {
  name: "OrderImport",
  components: { UploadExcel, Errors, Warnings, ConsigneeInfo, ShippingInfo, OrderInfo, ImportProgress },
  data () {
    return {
      api: order,
      userInfo: sessionStorage.getItem('userInfo'),
      emptyImg: require("@/static/images/no_data.png"),
      templateUrl: '/excelTemplate/订单导入模板.xlsx',
      total: 0,
      pageNo: 1,
      pageSize: 20,
      pageSizeOptions: [20, 50, 100],
      status: 1,
      pageList: [],
      tableHeaderData: [
        { label: "合同编号", type: "contractNo" },
        { label: "发货方", type: "fromInfo" },
        { label: "收货方", type: "toInfo" },
        { label: "订单信息", type: "orderInfo" },
        { label: "警告信息", type: "warnings" },
        { label: "订单状态", type: "success" },
        { label: "异常原因", type: "errors" },

        { label: "操作", type: "operation" }
      ],
      index: null,
      visible: false,
      subTaskObject: null,
      importsLength: null,
      loading: false
    };
  },
  computed: {
    ...mapState({
      // records: (state) => state.orderImport.importDatas,
      orderImportNames: (state) => state.orderImport.orderImportNames,
      tenantInfo: (state) => state.tenant.tenantInfo,
      updateGetterFlag: (state) => state.orderImport.updateGetterFlag,
    }),
    ...mapGetters('orderImport', ['getOrderImportData']),
    user () {
      return JSON.parse(this.userInfo)
    },
    useOrderImportData () {
      return this.getOrderImportData(this.user?.userId);
    },
    record () {
      return this.useOrderImportData;
    },
    orderImportName () {
      return this.orderImportNames[this.user?.userId] || null
    },
    isUpdateFlag () {
      return this.updateGetterFlag
    },
    taskUrl () {
      return `/tenant/task/{id}`
    },
  },
  watch: {
    record: {
      handler (val) {
        this.handleSizeChange();
        return val;
      },
      deep: true,
      immediate: true
    },
    orderImportNames: {
      handler (val) {
        return val;
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.loadTemplates();
  },
  methods: {
    ...mapActions({
      updatedOrderImportData: "orderImport/updatedOrderImportData",
    }),
    // 编辑订单
    edit (index) {
      let actionIndex = this.pageSize * (this.pageNo - 1) + index;

      this.$router.push({
        name: 'editOrder',
        params: { actionIndex }
      });
    },
    // 查询模板
    async loadTemplates () {
      let templateName = this.tenantInfo.echo && this.tenantInfo.echo?.OrderImport ? this.tenantInfo.echo?.OrderImport : 'OrderImport'
      const response = await admin.loadExcelTemplates();
      response.data.map(item => {
        if (item.name === templateName) {
          this.templateUrl = item.url;
        }
      })
    },
    // 下载模板
    download (url) {
      let newUrl = url.includes('https') ? url : url.replace('http', 'https')
      window.location.href = newUrl;
    },
    // 解析方法调用状态
    messageStatus ({ status, imports, name }) {
      this.importsLength = imports?.length
      this.status = status;
      const { userId } = this.user
      if (imports) {
        this.updatedOrderImportData({ userId, importData: imports })
        this.$store.commit("orderImport/ORDERIMPORTNAME", { name: name, userId: userId });
        // this.$store.commit("orderImport/ORDERIMPORT", { importData: imports, userId: userId });
      }
    },
    handleSizeChange () {
      this.total = this.record.length;
      this.pageList = this.record.slice(
        (this.pageNo - 1) * this.pageSize,
        this.pageNo * this.pageSize
      );
    },
    handleCurrentChange () {
      this.total = this.record.length;
      this.pageList = this.record.slice(
        (this.pageNo - 1) * this.pageSize,
        this.pageNo * this.pageSize
      );
    },
    handleRefresh () {
      this.updatedOrderImportData({ userId: this.user?.userId, importData: [] })
    },
    async submit () {
      this.loading = true;
      let flag = false;
      this.record.map(item => {
        if (!item.success) {
          flag = true;
        }
      })
      if (flag) {
        this.loading = false;
        return this.$message.error("订单状态全部为正常才可提交！");
      }
      let { data } = await order.submitImportExcel({
        name: this.orderImportName || "订单导入",
        imports: this.record
      }).catch(err => {
        this.loading = false;
        console.log("err", err)
      })
      this.loading = false;
      if (data.success) {
        if (data?.taskId) {
          const component = {
            taskUrl: this.taskUrl,
            count: this.importsLength || 0,
            id: data?.taskId
          };
          this.subTaskObject = component
          this.visible = true
          return
        }
        this.$message({ type: "success", message: "导入成功" });
        this.updatedOrderImportData({ userId: this.user?.userId, importData: [] })
      } else {
        // this.$message({ type: "error", message: "导入失败" });
        this.$message({ type: "error", message: data?.message });
        this.$store.commit("orderImport/ORDERIMPORTNAME", { orderImportName: data.name, userId: this.user?.userId });
        this.$store.commit("orderImport/ORDERIMPORT", { importData: data.imports, userId: this.user?.userId });
      }
    },
    // 取消导入
    handleCancel () {
      const { userId } = this.user
      this.updatedOrderImportData({ userId, importData: [] })
      this.$store.commit("orderImport/ORDERIMPORTNAME", { orderImportName: null, userId });
      // this.$router.back();
    }
  },
  // beforeDestroy () {
  //   this.$store.commit("orderImport/ORDERIMPORT", []);
  // }
};
</script>
<style lang="scss" scoped>
/deep/.el-table {
  font-size: 14px;
}
/deep/ .contractNo {
  vertical-align: top !important;
}
.box {
  background: var(--prev-bg-white);
  padding: 20px;
  height: calc(100vh - 120px);
  // overflow: auto;
}
.button_group {
  text-align: right;
}
.content_sty {
  text-align: center;
  line-height: 100px;
}
.import-results {
  font-size: 16px;
}
.text-center {
  span {
    width: 100px;
  }
}
.box-wrap {
  height: calc(100vh - 180px);
}
.order-import-pag {
  text-align: right;
  padding-top: 10px;
}
.empty_img {
  padding-top: 100px;
}
.tips {
  font-size: 16px;
  line-height: 60px;
  color: var(--prev-color-text-lightgrey);
}
.tips_1 {
  text-align: center;
  font-size: 24px;
  color: var(--prev-color-text-lightgrey);
}
.mt130 {
  margin-top: 130px;
}
.mr20 {
  margin-right: 20px;
}
/**
 * 火狐tooltip不显示问题
 */
.tooltipSty {
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline;
}
</style>
